<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Extracts Controller
 *
 * @property \App\Model\Table\ExtractsTable $Extracts
 */
class ExtractsController extends AppController
{
    public $html;
    public $error;
    public $status;

    public function init_curl_params()
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_PROXY, '10.1.248.1:82');
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0');
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        return ($ch);
    }

    public function exec_curl($ch, $url)
    {      
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array());  
        curl_setopt($ch, CURLOPT_URL, $url);
        $this->html = curl_exec($ch);
    }

    public function getElementsByClass(&$parentNode, $tagName, $className) {
        $nodes=array();
    
        $childNodeList = $parentNode->getElementsByTagName($tagName);
        for ($i = 0; $i < $childNodeList->length; $i++) {
            $temp = $childNodeList->item($i);
            if (stripos($temp->getAttribute('class'), $className) !== false) {
                $nodes[]=$temp;
            }
        }   
        return $nodes;
    }

    public function readxml() {
        $path = WWW_ROOT . 'files';
        $filename = '20180118_101716_2377078511295.xml';
        $file = $path . DS . $filename;
        
        $xml = file_get_contents($file, true);
        //debug($xml);
        $dom = new \DOMDocument(); //to parse html using DOMDocument
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
        $dom->loadXML($xml); //Loaded the html string we took from simple xml
 
        
        $nodes = $dom->getElementsByTagName('KOPPLUNG_LANG_BEZEICHNUNG');
        //debug($nodes->length);
        foreach ($nodes as $node) {
            $node->textContent = 'Anonym';
            //foreach($node->childNodes as $child ) {
            //    debug($child->nodeName);
            //    debug($child->nodeValue);
            //}
               //$node->getElementsByTagName('KOPPLUNG_LANG_BEZEICHNUNG')->item(0)->textContent = 'Anonym';
            
             
        }

        //die;

        $dom->saveXML(); // This will return the XML as a string
        $newfile = $file . '.new';
        $dom->save($newfile); // This saves the XML to a file

        $newcontent = file_get_contents($newfile, true);
        $this->viewBuilder()->layout('ajax');
        $this->set('content',$newcontent);

        
    }

    public function generate() {
        $snr = '9310';
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $random_string_length = 4;
        $string = '';
        $max = strlen($characters) - 1;
        for ($i = 0; $i < $random_string_length; $i++) {
             $string .= $characters[mt_rand(0, $max)];
        }
        $millis = round(microtime(true) * 1000);
         
        $string_ohne = $snr . $string . $millis; 
        //debug($string_ohne);
        $good = '9310QEKU15162667399540879';
        debug($good);

        $string_ohne = '9310QEKU1516266739954';
        debug($string_ohne);
        $hash = str_pad(hexdec(hash('adler32',$string_ohne)) % 9857, 4, '0', STR_PAD_LEFT);
        debug($hash);
        $string_mit = $string_ohne . $hash;
        debug($string_mit);
        die;

    }

    public function import()
    {  
        $ch = $this->init_curl_params();
        echo 'Hallo';
        $types = array('weibliche-vornamen','maennliche-vornamen','nachnamen','strassen');
        $alphas = range('a', 'z');
        debug($alphas);

        foreach($types as $type) {
            foreach($alphas as $alpha) {
                $url = 'http://www.namen-liste.de/' . $type . '-' .$alpha .'/';
                echo '<p>' . $url . '</p>';
                $this->exec_curl($ch, $url);
                $htmlParser = new \DOMDocument(); //to parse html using DOMDocument
                libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
                $htmlParser->loadHTML($this->html); //Loaded the html string we took from simple xml
                $htmlParser->preserveWhiteSpace = false;

                $nodes = $this->getElementsByClass($htmlParser, 'span' , 't4');
                foreach($nodes as $node) {
                    debug($node->nodeValue);
                    $extract = $this->Extracts->newEntity();
                    $extract->type = $type;
                    $extract->value = $node->nodeValue;
                    $this->Extracts->save($extract);
                }
            }
        }

        

    }

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $extracts = $this->paginate($this->Extracts);

        $this->set(compact('extracts'));
        $this->set('_serialize', ['extracts']);
    }

    /**
     * View method
     *
     * @param string|null $id Extract id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $extract = $this->Extracts->get($id, [
            'contain' => []
        ]);

        $this->set('extract', $extract);
        $this->set('_serialize', ['extract']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $extract = $this->Extracts->newEntity();
        if ($this->request->is('post')) {
            $extract = $this->Extracts->patchEntity($extract, $this->request->data);
            if ($this->Extracts->save($extract)) {
                $this->Flash->success(__('The extract has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The extract could not be saved. Please, try again.'));
        }
        $this->set(compact('extract'));
        $this->set('_serialize', ['extract']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Extract id.
     * @return \Cake\Network\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $extract = $this->Extracts->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $extract = $this->Extracts->patchEntity($extract, $this->request->data);
            if ($this->Extracts->save($extract)) {
                $this->Flash->success(__('The extract has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The extract could not be saved. Please, try again.'));
        }
        $this->set(compact('extract'));
        $this->set('_serialize', ['extract']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Extract id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $extract = $this->Extracts->get($id);
        if ($this->Extracts->delete($extract)) {
            $this->Flash->success(__('The extract has been deleted.'));
        } else {
            $this->Flash->error(__('The extract could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}
