<?php

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class LinksTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('Users');
        $this->hasMany('Statistics');
        $this->addBehavior('Timestamp');
    }

    public function validationDefault(Validator $validator)
    {
        $validator
            //->requirePresence('title')
            //->notEmpty('title', __('Please add a title.'))
            ->notEmpty('url', 'Please add a URL.')
            ->add('url', 'url', [
                'rule' => 'url',
                'message' => __('URL must be valid.')
            ])
            ->add('url', 'uniqueURL', [
                'rule' => function ($value, $context) {
                    $aliasCount = $this->find('all')
                        ->where(['url' => $value])
                        ->where(['user_id' => $context['data']['user_id']])
                        ->count();
                    if ($aliasCount > 0) {
                        return false;
                    }
                    return true;
                },
                    'message' => __('This link is already existing.')
                ])
                ->add('url', 'disallowedDomains', [
                    'rule' => function ($value, $context) {

                        $disallowed_domains = explode(',', get_option('disallowed_domains'));

                        $disallowed_domains[] = env('HTTP_HOST');

                        $main_domain = parse_url($value, PHP_URL_HOST);

                        if (in_array(strtolower($main_domain), $disallowed_domains)) {
                            return false;
                        }
                        return true;
                    },
                    'message' => __('This domain is not allowed on our system.')
                ])
                ->requirePresence('alias', 'create')
                ->notEmpty('alias', __('Please add an alias.'))
                ->add('alias', 'alphaNumeric', [
                    'rule' => 'alphaNumeric',
                    'message' => __('Alias should be a alpha numeric value')
                ])
                ->add('alias', 'unique', [
                    'rule' => 'validateUnique',
                    'provider' => 'table',
                    'message' => __('Alias already exists.')
                ]);
            //->requirePresence('short_description')
            //->notEmpty('short_description', __('Please, enter s short description about your link.'));

            return $validator;
    }

    public function validationReport(Validator $validator)
    {
        //$validator = $this->validateDefault($validator);
        return $validator
            ->notEmpty('reason', __('Please select a reason to report.'))
            ->add('reason', 'inList', [
                'rule' => ['inList', ['404', 'dead_links', 'no_links', 'masked_links', 'premium_links', 'virus', 'other']],
                'message' => __('Please enter a valid reason')
            ]);
    }

    public function isOwnedBy($alias, $user_id)
    {
        return $this->exists(['alias' => $alias, 'user_id' => $user_id]);
    }

    public function geturl()
    {
        do {
            $min = get_option('alias_min_length', 4);
            $max = get_option('alias_max_length', 8);

            $numAlpha = rand($min, $max);
            $out = $this->generateurl($numAlpha);
            while ($this->checkReservedAuto($out)) {
                $out = $this->generateurl($numAlpha);
            }
            $alias_count = $this->find('all')
                ->where(['alias' => $out])
                ->count();
        } while ($alias_count > 0);
        return $out;
    }

        //http://blog.justni.com/creating-a-short-url-service-using-php-and-mysql/
    public function generateurl($numAlpha)
    {
        $listAlpha = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $generateurl = '';
        $i = 0;
        while ($i < $numAlpha) {
            $random = mt_rand(0, strlen($listAlpha) - 1);
            $generateurl .= $listAlpha{$random};
            $i = $i + 1;
        }
        return $generateurl;
    }

    public function checkReservedAuto($keyword)
    {
        //$reserved_aliases = explode( ',', Configure::read( 'Option.reserved_aliases' ) );
        $reserved_aliases = [];
        if (in_array($keyword, $reserved_aliases)) {
            return true;
        }
        return false;
    }
}
