// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"bytes"
	"os"

	"github.com/BurntSushi/toml"
	"github.com/juju/errors"
	"github.com/siddontang/go/ioutil2"
)

// PersistentTable represents persistent table struct
type PersistentTable struct {
	filename string
	Tables   map[string][]*table `toml:"tables" json:"tables"`
}

func newPersistentTable(filename string) *PersistentTable {
	return &PersistentTable{filename: filename, Tables: make(map[string][]*table)}
}

// Save saves in disk
func (p *PersistentTable) Save() error {
	var buf bytes.Buffer
	e := toml.NewEncoder(&buf)
	err := e.Encode(p)
	if err != nil {
		return errors.Trace(err)
	}

	err = ioutil2.WriteFileAtomic(p.filename, buf.Bytes(), 0644)
	if err != nil {
		return errors.Trace(err)
	}

	return nil
}

// Load loads schema in disk
func (p *PersistentTable) Load() error {
	file, err := os.Open(p.filename)
	if os.IsNotExist(errors.Cause(err)) {
		return nil
	}
	if err != nil {
		return errors.Trace(err)
	}
	defer file.Close()

	_, err = toml.DecodeReader(file, p)
	return errors.Trace(err)
}
