/*
* Naamari-lautta - a wrapper of console cloud clients for Naamari
* Copyright (c) 2015-2017 Sunkware
* Key FP = 6B6D C8E9 3438 6E9C 3D97  56E5 2CE9 A476 99EF 28F6
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* [ WWW: sunkware.org ]                         [ E-MAIL: sunkware@gmail.com ]
 */

package main

import (
	"encoding/json"
	"errors"
	"io/ioutil"
)

type CloudClientSyntax struct {
	AppName string
	// In JSON, only one of these 2 blocks is allowed
	UploadAppName   string
	DownloadAppName string
	RemoveAppName   string

	UploadCmd   string
	DownloadCmd string
	RemoveCmd   string
}

func LoadClientSyntax(jsonFileName string) (cloudClientSyntax CloudClientSyntax, err error) {

	var jsonFileData []byte

	jsonFileData, err = ioutil.ReadFile(jsonFileName)

	if err != nil {
		err = errors.New("cannot read file")
		return
	}

	err = json.Unmarshal(jsonFileData, &cloudClientSyntax)

	if err != nil {
		err = errors.New("cannot json-unmarshal file data")
		return
	}

	// Checking for simple errors...

	if cloudClientSyntax.AppName != "" && (cloudClientSyntax.UploadAppName != "" || cloudClientSyntax.DownloadAppName != "" || cloudClientSyntax.RemoveAppName != "") {
		err = errors.New("single app name XOR upload, download, remove app names must be specified!")
		return
	}

	if cloudClientSyntax.AppName != "" { // single app for 3 operations
		cloudClientSyntax.UploadAppName = cloudClientSyntax.AppName
		cloudClientSyntax.DownloadAppName = cloudClientSyntax.AppName
		cloudClientSyntax.RemoveAppName = cloudClientSyntax.AppName

	} else { // different apps
		if cloudClientSyntax.UploadAppName == "" {
			err = errors.New("upload app name not specified!")
			return
		}
		if cloudClientSyntax.DownloadAppName == "" {
			err = errors.New("download app name not specified!")
			return
		}
		if cloudClientSyntax.RemoveAppName == "" {
			err = errors.New("remove app name not specified!")
			return
		}
	}

	if cloudClientSyntax.UploadCmd == "" {
		err = errors.New("upload command-line not specified!")
		return
	}

	if cloudClientSyntax.DownloadCmd == "" {
		err = errors.New("download command-line not specified!")
		return
	}

	if cloudClientSyntax.RemoveCmd == "" {
		err = errors.New("remove command-line not specified!")
		return
	}

	return
}
