package capping


import (
	"net/http"
	"strings"
	"strconv"
	"fmt"
	    "time"
	)
	
	
func CookieValue(r *http.Request , str string) string {
	
	cookie, err := r.Cookie(str)
        if err != nil {
                  return ""
 
          
        }
          return cookie.Value

	
}
	
func CheckCaping(r *http.Request, id int , Block int, Capping int , Session_capping int ,types string) bool {
	 
	 
	 
	 if Capping != 0 ||  ( Block !=0 && Session_capping !=0 ) {
		 
	  
	  
	rxCap := ""
	rxCapSes := ""
	rxCapBloc := ""
	
	if types == "zone" {
		
	rxCap = CookieValue(r,"OAZCAP")
	rxCapSes = CookieValue(r,"OASZCAP")
	rxCapBloc = CookieValue(r,"OAZBLOCK")
	
	} else  if types == "banner" { 
	
	rxCap = CookieValue(r,"OACAP")
	rxCapSes = CookieValue(r,"OASCAP")
	rxCapBloc = CookieValue(r,"OABLOCK")
		
	} else {
		
	rxCap = CookieValue(r,"OACCAP")
	rxCapSes = CookieValue(r,"OASCCAP")
	rxCapBloc = CookieValue(r,"OACBLOCK")
	}
	
	 
 

	rxCap_c := "0"
	rxCapSes_c := "0" 
	rxCapBloc_c := "0"  

	
	if rxCap !="" {

		rxCapval := strings.Split(rxCap, "_") 
		

		    for index, element := range rxCapval{
						if index !=0 {	}	
				rxCapvalSp := strings.Split(element, ".")
				 
				if  rxCapvalSp[0] == strconv.Itoa(id) {
					rxCap_c =rxCapvalSp[1]

				}
			}

	}
	
	
	if rxCapSes !="" {

		rxCapSesval := strings.Split(rxCapSes, "_") 
		

		    for index, element := range rxCapSesval{
						if index !=0 {	}	
				rxCapSesvalSp := strings.Split(element, ".")
				 
				if  rxCapSesvalSp[0] == strconv.Itoa(id) {
					rxCapSes_c = rxCapSesvalSp[1]

				}
			}

	}
	
	
	if rxCapBloc !="" {

		rxCapBlocval := strings.Split(rxCapBloc, "_") 
		

		    for index, element := range rxCapBlocval{
						if index !=0 {	}	
				rxCapBlocvalSp := strings.Split(element, ".")
				 
				if  rxCapBlocvalSp[0] == strconv.Itoa(id) {
					rxCapBloc_c = rxCapBlocvalSp[1]

				}
			}

	}
	
	
	
	rxCap_sc , err := strconv.Atoi(rxCap_c)
	rxCapSes_sc , err := strconv.Atoi(rxCapSes_c)
	rxCapBloc_sc , err := strconv.ParseInt(rxCapBloc_c, 10, 64)
	rxCapBloc_sc = rxCapBloc_sc + int64(Block)
	
    currnttime := makeTimestamp()
			
							     fmt.Println(rxCapBloc_sc)
							     fmt.Println(currnttime)

	if err == nil {
	
	if(Capping > rxCap_sc ) {
		
	
	if rxCapBloc_sc > currnttime   {
		
				     fmt.Println("not expie")

		    if Session_capping > rxCapSes_sc {
								     fmt.Println("have counr")

			return true	
			
		} else {
				     fmt.Println("count expire")

			return false	
		}
	}
	
	if rxCapBloc_sc < currnttime && Session_capping != 0  {
				     fmt.Println("is expired & start new")

		return true	
	} 
	
	
	}
	
	
	} 
	
	
	return false
	
	 
	 }
	 
	 
	 return true
}



func makeTimestamp() int64 {
    now := time.Now()      // current local time
sec := now.Unix()      // number of seconds since January 1, 1970 UTC
return sec 
}



