<?php

use Illuminate\Database\Seeder;
use App\Models\Country;
use App\Models\CountryLanguage;
use App\Models\GenericBackoffice\WebsiteObject;
use App\Models\GenericBackoffice\WebsiteObjectLanguage;

class CountriesTableSeeder extends BaseSeeder
{

    private $countryListEN;
    //! We aren't using PT lang at the moment
    //private $countryListPT;

    public function __construct()
    {
        // Lists taken from
        // https://github.com/umpirsky/country-list

        $this->countryListEN = json_decode(file_get_contents(resource_path('json/en/countries.json')), true);
        //! We aren't using PT lang at the moment
        //$this->countryListPT = json_decode(file_get_contents(resource_path('json/pt/countries.json')), true);
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $countries = $this->_getData();
        foreach ($countries as $countryInfo) {
            $countryModel = Country::where('iso_code', $countryInfo['iso_code'])->first();
            if (is_null($countryModel)) {
                $countryModel = Country::create([
                    'iso_code' => $countryInfo['iso_code']
                ]);
            }

            $websiteObject = $this->createWebsiteObject($countryModel, 'country', $countryInfo['languages']['en']);
            $countryModel->websites()
                ->save($websiteObject);

            forEach ($countryInfo['languages'] as $key => $countryLang) {
                CountryLanguage::updateOrInsert([
                    'country_id'  => $countryModel->id,
                    'language_id' => $key
                ], [
                    'title'        => $countryLang,
                    'country_name' => $countryLang
                ]);
                $this->createWebsiteObjectLanguage($websiteObject, $key);
            }
        }
    }

    protected function _getData()
    {
        // Organize all the data
        $countryList = [];
        foreach ($this->countryListEN as $key => $country) {
            $countryList[] = [
                'iso_code'  => $key,
                'languages' => [
                    'en'    => $country,
                ]
            ];
        }

        return $countryList;
    }
}
