module filtermanager {
	
	export class ConnectionManager{
		
		// Replace with your client ID from the developer console.
  		private CLIENT_ID: string = '968770435425-loc10si1h7ra3d6jvkfkkpcoihhp96tu.apps.googleusercontent.com';

		// Set authorized scope.
		private SCOPES: Array<string> = ['https://www.googleapis.com/auth/analytics.edit'];
		
		
		constructor(private gam: FilterManager){}
		
		
		public authorize(): Promises.Promise {					
			var authData = {
				client_id: this.CLIENT_ID,
				scope: this.SCOPES,
				immediate: false
			};
			var d = new Promises.Deferred();
			gapi.auth.authorize(authData, (response: GoogleApiOAuth2TokenObject) => {
				if(response.error) {
					d.reject(response.error);
				}
				else {
					d.fulfill('fulfill auth');
				}
			});
			return d.promise();
		}
		public loadAnalytics(): Promises.Promise {
			var d = new Promises.Deferred() 
			
			gapi.client.load('analytics', 'v3', () => {
				if(gapi.client.analytics){
					d.fulfill('yes');
				}
				else {
					d.reject('no')
				}
			});
			
			return d.promise();
			
			
		}
  
    //Funkce get na získání jednotlivých dat filtrů    
        
	 public makeApiCallAccountFiltersGet(AccId:number, FilterId:Array<number>):Promises.Promise {
		
		 var d = new Promises.Deferred() 
         var batch = gapi.client.newBatch();
		 var result;			
					if(gapi.client.analytics){
						
                        		 
                         
                        for (var i = 0; i < FilterId.length; i++) {
                             var downloadedJSON:any = {
							'accountId': AccId,
							'filterId': FilterId[i]
						  };
						
						  var apiQuery1 = gapi.client.analytics.management.filters.get(downloadedJSON);
                          batch.add(apiQuery1);
                          }

                         batch.then((param)=>{d.fulfill(param)},()=>{d.reject("neprošel batch s requesty")}); 

						}
					else{
						d.reject(result)
						}
			 
			 return d.promise();
	 }
	 
     
     // Funkce na vložení filter linků
     
    	 public makeApiCallAccountFilterLinksInsert(ProfId:number,PropId:number,AccId:number, FilterId:Array<number>):Promises.Promise {
		 debugger;
		 var d = new Promises.Deferred() 
         var batch = gapi.client.newBatch();
		 var result;			
					if(gapi.client.analytics){
                        for (var i = 0; i < FilterId.length; i++) {
                             var downloadedJSON:any = {
								    'accountId': AccId,
                                    'webPropertyId': PropId,
                                    'profileId': ProfId,
                                    'resource':{
                                        'filterRef':{
                                            'id': FilterId[i]
                                        },
                                        'rank':255
                                    }
						  };
						
						  var apiQuery1 = gapi.client.analytics.management.profileFilterLinks.insert(downloadedJSON);
                          batch.add(apiQuery1);
                          }

                         batch.then((param)=>{d.fulfill(param)},()=>{d.reject("neprošel batch s requesty")}); 

						}
					else{
						d.reject(result)
						}
			 
			 return d.promise();
	 } 
     
     
     
     
	 public makeApiCallAccountFiltersList(AccId:number):Promises.Promise {
		
		 var d = new Promises.Deferred() 
         var batch = gapi.client.newBatch();
		 var result;			
					if(gapi.client.analytics){
                             var downloadedJSON:any = {
							'accountId': AccId
						  };
						  var apiQuery1 = gapi.client.analytics.management.filters.list(downloadedJSON);
                          batch.add(apiQuery1);
                         batch.then((param)=>{d.fulfill(param)},()=>{d.reject("neprošel batch s requesty")}); 
                        }
						
					else{
						d.reject(result)
						}
			 return d.promise();
	 }

	 
	 	 public makeApiCallProfileFilterLinks(ProfId:number,PropId:number,AccId:number):Promises.Promise {
		 debugger;
			var d = new Promises.Deferred() 
            debugger;
			var downloadedJSON2:any = {
				'accountId': AccId,
				'webPropertyId': PropId,
				'profileId': ProfId
				};
			if(gapi.client.analytics){
				var apiQuery2= gapi.client.analytics.management.profileFilterLinks.list(downloadedJSON2);
				d.fulfill(apiQuery2);
			}
			else{
				d.reject(apiQuery2.message)
				}
             return d.promise();
	 }
              public makeApiCallInsertFilters2(AccId:number):Promises.Promise {
            var batch = gapi.client.newBatch();
			var d = new Promises.Deferred();
			var downloadedJSON2:any = [{
                        "accountId": AccId,
                        "resource": {
                            "type": "LOWERCASE",
                            "name": "Malá písmena pro zdroj",
                            "kind": "analytics#filter", 
                            "lowercaseDetails": {
                                "field": "CAMPAIGN_SOURCE"
                            }
                        }
                    },
                    {
                        "accountId": AccId,
                        "resource": {
                            "type": "LOWERCASE",
                            "name": "Malá písmena pro medium",
                            "kind": "analytics#filter", 
                            "lowercaseDetails": {
                                "field": "CAMPAIGN_MEDIUM"
                            }
                        }
                    },
                    {
                        "accountId": AccId,
                        "resource": {
                            "type": "LOWERCASE",
                            "name": "Malá písmena pro kampaň",
                            "kind": "analytics#filter", 
                            "lowercaseDetails": {
                                "field": "CAMPAIGN_NAME"
                            }
                        }
                    },
                    {
                        "accountId": AccId,
                        "resource": {
                            "type": "LOWERCASE",
                            "name": "Malá písmena pro term",
                            "kind": "analytics#filter", 
                            "lowercaseDetails": {
                                "field": "CAMPAIGN_TERM"
                            }
                        }
                    },
                    {
                        "accountId": AccId,
                        "resource": {
                            "type": "LOWERCASE",
                            "name": "Malá písmena pro content",
                            "kind": "analytics#filter", 
                            "lowercaseDetails": {
                                "field": "CAMPAIGN_CONTENT"
                            }
                        }
                    },
                   {
                   "accountId": AccId,
                   "resource": {
                        "name": "Nahrazeni sklik za seznam",
                        "type": "SEARCH_AND_REPLACE",
                        "searchAndReplaceDetails": {
                            "searchString": "^sklik$",
                            "replaceString": "seznam",
                            "caseSensitive": false
                            }           
                        }
                    }
              
                    ]
                    for (var i = 0; i < downloadedJSON2.length; i++) {
                    var apiQuery2= gapi.client.analytics.management.filters.insert(downloadedJSON2[i]);
					batch.add(apiQuery2);
                    
            }
				
				if(gapi.client.analytics){

                    
                    batch.then(()=>{d.fulfill(apiQuery2)},()=>{d.reject("Neprošlo poslání filtrů")})
                    console.log(apiQuery2.result);
					}
				else{
					d.reject(apiQuery2.message)
					}
             return d.promise();
	 }
              public makeApiCallInsertFilters1(AccId:number):Promises.Promise {
		   
            var batch = gapi.client.newBatch();
			var d = new Promises.Deferred();
			var downloadedJSON2:any = [ {
                   "accountId": AccId,
                   "resource": {
                        "name": "Nahrazeni adwords za google",
                        "type": "SEARCH_AND_REPLACE",
                        "searchAndReplaceDetails": {
                            "searchString": "^adwords$",
                            "replaceString": "google",
                            "caseSensitive": false
                            }           
                        }
                    },
                    {
                   "accountId": AccId,
                   "resource": {
                        "name": "Nahrazeni adwords za google",
                        "type": "SEARCH_AND_REPLACE",
                        "searchAndReplaceDetails": {
                            "searchString": "^ppc$",
                            "replaceString": "cpc",
                            "caseSensitive": false
                            }           
                        }
                    }
                    ]
                    for (var i = 0; i < downloadedJSON2.length; i++) {
                    var apiQuery2= gapi.client.analytics.management.filters.insert(downloadedJSON2[i]);
					batch.add(apiQuery2);
                    
            }
				
				if(gapi.client.analytics){

                    
                    batch.then(()=>{d.fulfill(apiQuery2)},()=>{d.reject("Neprošlo poslání filtrů")})
                    console.log(apiQuery2.result);
					}
				else{
					d.reject(apiQuery2.message)
					}
             return d.promise();
	 }	 	
         public makeApiCallInsertFilters(AccId:number,Domain:string):Promises.Promise {
		    debugger;
            var batch = gapi.client.newBatch();
			var d = new Promises.Deferred();
            var firstPartOfDomain, secondPartOfDomain, thirdPartOfDomain;
            if(Domain.length<=2){
                secondPartOfDomain = Domain[0];
                thirdPartOfDomain = Domain[1];
            }else{
                firstPartOfDomain = Domain[0];
                secondPartOfDomain = Domain[1];
                thirdPartOfDomain = Domain[2];
            };
			var downloadedJSON2:any = [{
                "accountId": AccId,
                "resource": {
                    "type": "EXCLUDE",
                    "name": "Nezahrnout SPAM boty 3",
                    "kind": "analytics#filter", 
                    "excludeDetails": {
                        "kind": "analytics#filterExpression",
                        "field": "REFERRAL",
                        "matchType": "MATCHES",
                        "expressionValue": "(^|\\.)econom\\.co|(^|\\.)(anal\\-acrobats|sexyteens)\\.hol\\.es|(^|\\.)(buy\\-cheap\\-online|forum69|ranksonic)\\.info|pornhub\\-forum\\.uni\\.me|acads\\.net|(^|\\.)(4webmasters|anticrawler|forum20|smailik|guardlink|humanorightswatch|ranksonic)\\.org|ok\\.ru",
                        "caseSensitive": false
                        }
                    }
                }, 
                {
                "accountId": AccId,
                "resource": {
                    "type": "EXCLUDE",
                    "name": "Nezahrnout SPAM boty 1",
                    "kind": "analytics#filter", 
                    "excludeDetails": {
                        "kind": "analytics#filterExpression",
                        "field": "REFERRAL",
                        "matchType": "MATCHES",
                        "expressionValue": "(^|\\.)(7makemoneyonline|best\\-seo\\-(offer|solution)|bestwebsitesawards|blackhatworth|brakehawk|buttons\\-for\\-(|your\\-)website|darodar|event\\-tracking|(free|simple)\\-share\\-buttons|get\\-free\\-traffic\\-now|googlsucks|hulfingtonpost|ilovevitaly|iminent)\\.com",
                        "caseSensitive": false
                    }}
                },
                {
                "accountId": AccId,
                "resource": {
                    "type": "EXCLUDE",
                    "name": "Nezahrnout SPAM boty 2",
                    "kind": "analytics#filter", 
                    "excludeDetails": {
                        "kind": "analytics#filterExpression",
                        "field": "REFERRAL",
                        "matchType": "MATCHES",
                        "expressionValue": "(^|\\.)(kabbalah\\-red\\-bracelets|kambasoft|makemoneyonline|masterseek|o\\-o\\-6\\-o\\-o|priceg|savetubevideo|semalt|social\\-buttons|theguardlan|webmaster\\-traffic)\\.com|(^|\\.)((pornhub|youporn)\\-forum|rapidgator\\-porn)\\.ga",
                        "caseSensitive": false
                    }}
                    },{
                        
                        "accountId": AccId,
                        "resource": {
                        "type": "EXCLUDE",
                        "name": "Zahrnout jen "+ secondPartOfDomain +"."+ thirdPartOfDomain,
                        "kind": "analytics#filter", 
                        "excludeDetails": {
                            "kind": "analytics#filterExpression",
                            "field": "REFERRAL",
                            "matchType": "MATCHES",
                            "expressionValue": "(^|\\.)"+secondPartOfDomain+"\\."+thirdPartOfDomain+"$",
                            "caseSensitive": false
                            }
                        }
                    },
                    {
                        "accountId": AccId,
                        "resource": {
                            "type": "EXCLUDE",
                            "name": "Nezahrnout SPAM boty 4",
                            "kind": "analytics#filter", 
                            "excludeDetails": {
                                "kind": "analytics#filterExpression",
                                "field": "REFERRAL",
                                "matchType": "MATCHES",
                                "expressionValue": "(^|\\.)(\ttpc.googlesyndication|video--production|success-seo|get-free-social-traffic|floating-share-buttons)\\.com",
                                "caseSensitive": false
                            }
                        }
                    }
                    ]
                    for (var i = 0; i < downloadedJSON2.length; i++) {
                    var apiQuery2= gapi.client.analytics.management.filters.insert(downloadedJSON2[i]);
					batch.add(apiQuery2);
                    
            }
				
				if(gapi.client.analytics){

                    
                    batch.then(()=>{d.fulfill(apiQuery2)},()=>{d.reject("Neprošlo poslání filtrů")})
                    console.log(apiQuery2.result);
					}
				else{
					d.reject(apiQuery2.message)
					}
             return d.promise();
	 }
      public handleCoreReportingResults(apiQuery):Promises.Promise {
					var d = new Promises.Deferred() 
					if (!apiQuery.error) {
						d.fulfill(apiQuery);
					} else {
						d.reject("no");
						alert('There was an error: ' + apiQuery.message);
					} 
					
					return d.promise();
			}  
	}
}