<?php

namespace CouponsPlus\App\Plugin;

use CouponsPlus\Original\Characters\StringManager;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\Original\Environment\Env;

class InstalledVersions
{
    /**
     * @var Collection
     */
    protected $installedVersions;

    public function __construct()
    {
        $this->installedVersions = Collection::create(
            json_decode(get_option($this->getOptionKey(), $default = '[]'))
        )->map(function(array $versionData) {
            list($version, $date) = $versionData;
            return new InstalledVersion($version, $date);
        });
    } 
    
    public function get() : Collection
    {
        return $this->installedVersions;
    }

    public function add(InstalledVersion $installedVersion)
    {
        $this->installedVersions->push($installedVersion);
    }

    public function hasCurrentVersion() : bool
    {
        return (boolean) $this->get()->find(function(InstalledVersion $installedVersion) {
            return $installedVersion->getVersion()->is($this->getCurrentVersion());
        });
    }

    public function getCurrentVersion() : StringManager
    {
        if( ! function_exists('get_plugin_data') ){
            require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
        }

        (object) $CouponsPlusPluginData = get_plugin_data(Env::directory().Env::settings()->app->pluginFileName.'.php');

        return new StringManager($CouponsPlusPluginData['Version']);
    }

    public function save()
    {
        update_option(
            $this->getOptionKey(), 
            $this->installedVersions->asJson()->get()
        );
    }

    protected function getOptionKey() : string
    {
        return Env::getWithPrefix('versions');   
    }
}