<?php

namespace MGModule\DNSManager2\mgLibs\custom\dns\utils;

use MGModule\DNSManager2\mgLibs\custom\dns\record\Record;
use MGModule\DNSManager2\models\custom\reverse\Reverse;
use MGModule\DNSManager2\mgLibs\custom\dns\exceptions\DNSSubmoduleException;

class ReverseDNSHelper
{

    private static function getIPObject($ip)
    {
        if($ip instanceof IP)
            return $ip;
        return new IP($ip);
    }

    public static function reverseZoneName($ip)
    {
        $ip = self::getIPObject($ip);
        if($ip->isIPv4()) {
            $ip->reverse();
            return $ip->slice(1) . '.in-addr.arpa';
        } else {
            //return self::IPv6ToDotNotation($ip->slice(0)) . '.ip6.arpa';
            return self::IPv6ToDotNotation($ip->slice(0, IP::HALF)) . '.ip6.arpa';
        }
    }

    public static function reverseRecordName($ip)
    {
        $ip = self::getIPObject($ip);
        if($ip->isIPv4()) {
            $ip->reverse();
            return $ip->slice(0, 1);
        } else {
            return self::IPv6ToDotNotation($ip->slice(IP::HALF));
        }
    }

    public static function createPTRRecord($ip, $ttl, $value)
    {
        $record = new Record();
        $record->name = self::reverseRecordName($ip);
        $record->ttl = $ttl;
        $record->type = 'PTR';
        $record->createRDATAObject('PTR');
        $record->rdata->setFirstProperty($value);
        return $record;
    }
    
    private static function IPv6ToDotNotation($ip) {
        $ip = strrev(str_replace(':', '', $ip));
        return trim(chunk_split($ip, 1, '.'),'.');
    }
    
    public static function buildReverseFromARPA(Record $record,$domain)
    {
        $out            = array();
        $out['from']    = $record->rdata->ptrdname;
        $num            = explode('.',$record->name);
        $domain         = explode('in',$domain);
        $firstIpPart    = substr($domain[0],0,-1);
        $explodeFirstPart = explode('.',$firstIpPart);
        $reverseIp      = array_reverse($explodeFirstPart);
        $out['ip']      = implode('.',$reverseIp) . '.' . $num[0];
        $out['ttl']     = $record->ttl;

        return $out;  
    }
    
    public static function fromIP6Arpa($ip,$ptr)
    {  
        $secondPart = str_replace('.'.$ip.'.', '', $ptr);
        $ip         = str_replace('ip6.arpa', '' , $ip);
        $ip .= $secondPart;
        
        if(strlen($ip) !== 63)
        {
            throw new DNSSubmoduleException('Incorrect ip6.arpa form.');
        }
        
        $colon = 7;   
        $split = explode('.', $ip);
        $adress = array_reverse($split);
        
        for($i = $colon; $i > 0; $i--)
        {
            $index = $i * 4;
            array_splice($adress,$index,0,':');        
        }

        $ipv6 = implode('', $adress);
        
        return $ipv6;  
    } 
}