<?php
/**
 * Copyright (c) 2017 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

namespace App\Model;

use App\Entity\Contacts as ContactsEntity;
use App\Service\Config\Writer\PhpArray;

/**
 * Class Contacts
 * @package App\Model
 */
class Contacts
{
    const PATH_TO_CONTACTS = './config/autoload/contacts.global.php';

    const KEY_TO_MODIFY = 'contacts';
    /**
     * @param ContactsEntity $data
     */
    public function save(ContactsEntity $data)
    {
        if ($this->isExistConfig()) {
            $writer = new PhpArray();
            $writer->setUseBracketArraySyntax(true);
            $writer->toFile(realpath(self::PATH_TO_CONTACTS),
                [
                    self::KEY_TO_MODIFY => $data->toArrayForConfig()
                ]
            );
        }

    }

    /**
     * @return ContactsEntity
     * @throws \Exception
     */
    public function get()
    {
        $contacts = new ContactsEntity();
        if ($this->isExistConfig()) {

            $configTmp = include self::PATH_TO_CONTACTS;
            if (array_key_exists(self::KEY_TO_MODIFY, $configTmp)) {
                $contacts->setPhones($configTmp[self::KEY_TO_MODIFY][ContactsEntity::PHONES_KEY] ?? []);
                $contacts->setMails($configTmp[self::KEY_TO_MODIFY][ContactsEntity::MAILS_KEY] ?? []);
                $contacts->setSkypes($configTmp[self::KEY_TO_MODIFY][ContactsEntity::SKYPES_KEY] ?? []);
            } else {
            }
        }
        return $contacts;
    }

    /**
     * @return bool
     * @throws \Exception
     */
    protected function isExistConfig()
    {
        if (!realpath(self::PATH_TO_CONTACTS)) {
            throw new \Exception('KEY "' . self::KEY_TO_MODIFY . '" not found at config ' . realpath(self::PATH_TO_CONTACTS));
        }
        return true;
    }
}