<?php

/**
 * Class VcsSettingsModel
 */
class VcsSettingsModel extends Cf_Model
{
    const vcsSettingsResource = '/vcs/settings';
    const GIT_CFBS_VCS_TYPE = 'GIT_CFBS';

    /**
     * @return mixed
     * @throws Exception
     */
    public function getSettings()
    {
        $url = self::vcsSettingsResource;

        try {
            $json   = $this->getRestClient()->get($url);
            $result = $this->decorateSettingsResponse(json_decode($json)->data);

            return $result;
        } catch (Exception $e) {
            throw $e;
        }
    }

    public function isSshUrl($url)
    {
        $pattern = '/[^@]+@[^:]+:[^\/]+\/[^.]+\.git/';

        return (bool)preg_match($pattern, $url, $m);
    }

    private function decorateSettingsResponse($settings)
    {
        $this->load->helper('form');

        return [
            'vcsType'     => element_object('VCS_TYPE', $settings, 'GIT'),
            'gitServer'   => element_object('GIT_URL', $settings, null),
            'gitRefspec'  => element_object('GIT_REFSPEC', $settings, null),
            'projectSubdirectory'  => element_object('PROJECT_SUBDIRECTORY', $settings, null),
            'gitUsername' => element_object('GIT_USERNAME', $settings, null),
            'gitPassword' => element_object('GIT_PASSWORD', $settings, null)
        ];
    }

    /**
     * @param $data
     *
     * @return mixed
     * @throws Exception
     */
    public function createSettings($data)
    {
        $url      = self::vcsSettingsResource;
        $postData = $data;

        try {
            $json = $this->getRestClient()->post($url, $postData);
            return $json;
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * @param $filePath
     *
     * @return mixed
     * @throws Exception
     */
    public function readSshKey($filePath)
    {
        if ( ! is_readable($filePath)) {
            throw new Exception('Ssh key should be readable.');
        }
        $key = file_get_contents($filePath);
        return $key;
    }

    /**
     * @return mixed
     * @throws Exception
     */
    public function deleteSettings()
    {
        $url = self::vcsSettingsResource;

        try {
            $json = $this->getRestClient()->delete($url);

            return $json;
        } catch (Exception $e) {
            throw $e;
        }
    }

}