#!/usr/bin/python3
# -*- coding: utf-8 -*-

__author__ = 'suxoza'

'''
<!--style_container_for_compress-->
<!--script_container_for_compress-->
'''

import socket

def get_ip():
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.connect(("8.8.8.8", 80))
	ip = s.getsockname()[0]
	s.close()
	return ip

if get_ip() == '192.168.0.48':
	host_name = 'phall.local'
else:
	host_name = 'phall.loc'

host_name = 'new.kharagauli.ge'
class compress_files:

	def __init__(self):
		self.kwargs = options
		self.dir = 'http://'+host_name+'/'

		
		self.depricated_files = [
								 os.path.join(dir_,'templates/game_on/templates_1/help_page.tpl'),
								 os.path.join(dir_,'templates/game_on/templates_1/contact.tpl'),
								 os.path.join(dir_,'templates/game_on/templates_1/information_page.tpl'),
								 os.path.join(dir_,'templates/game_on/templates_1/questions.tpl'),
								 os.path.join(dir_,'moduls/questions/admin/templates_1/404.tpl'),
								 os.path.join(dir_,'moduls/query/admin/templates_1/index.tpl'),
								 os.path.join(dir_,'moduls/query/admin/templates_1/list.tpl'),
								 os.path.join(dir_,'moduls/query/admin/templates_1/new.tpl'),
								 os.path.join(dir_,'moduls/query/admin/templates_1/404.tpl'),
								 os.path.join(dir_,'moduls/banners/admin/templates_1/list.tpl'),
								 os.path.join(dir_,'moduls/banners/admin/templates_1/new.tpl'),
								 os.path.join(dir_,'moduls/banners/admin/templates_1/404.tpl'),
								 os.path.join(dir_,'moduls/small/site/templates_1/404.tpl'),
								 os.path.join(dir_,'moduls/small/admin/templates_1/index.tpl'),
								 os.path.join(dir_,'moduls/small/admin/templates_1/404.tpl'),
								 os.path.join(dir_,'moduls/big_logo/site/templates_1/list.tpl'),
								 os.path.join(dir_,'moduls/big_logo/site/templates_1/404.tpl'),
								 os.path.join(dir_,'moduls/big_logo/admin/templates_1/index.tpl'),
								 os.path.join(dir_,'moduls/big_logo/admin/templates_1/list.tpl'),
								 ]
		self.init__()


	def init__(self):
		print(self.kwargs)
		method = getattr(self,self.kwargs['command'])
		method()

	def restore(self):
		for root, dirs, files in os.walk(dir_):
			for file in files:
				if not file.endswith('.tpl'):continue
				file = os.path.join(root,file)
				if file.strip() in self.depricated_files or 'Smarty' in root:continue
				
				with fileinput.FileInput(file, inplace=True) as f:
					for line in f:
						if 'comment_for_compress' in line:
							print(line.replace('<!--comment_for_compress','').replace('comment_for_compress-->','').replace(' id="its_removed"',''),end = '')
						elif 'my_compressed_css_' in line:
							print('<!--style_container_for_compress-->')
						elif 'my_compressed_js_' in line:
							print('<!--script_container_for_compress-->')
						else:
							print(line, end = '')
				


			

	def replace(self):
		for root, dirs, files in os.walk(dir_):
			for file_ in files:
				if not file_.endswith('.tpl'):continue
				file = os.path.join(root,file_)
				if file in self.depricated_files or 'Smarty' in root:continue
				if file != '/var/www/kharagauli_new/templates/game_on/templates_1/base.tpl' or 'favicon' in file:continue
					 
				self.replace_progress(root, file, file_)
				
				


			

	def replace_progress(self, root, file, file_):
		styles = []
		scripts = []
		changed_scripts = []
		changed_styles = []
		with open(file, 'r') as r:
			for l in r.readlines():
				if '<script' in l and "src=" in l and 'my_compressed_js_' not in l:
					if "<!--" in l and 'its_removed' not in l:
						continue
					changed_scripts.append(l.strip())
				
				elif '<link' in l and "href=" in l and 'my_compressed_css_' not in l:
					if "<!--" in l and 'its_removed' not in l:
						continue
					changed_styles.append(l.strip())
					
		if not (len(changed_scripts) or len(changed_styles)):
			return

		print(file,len(changed_styles),len(changed_scripts))

		#continue
		file_enswith = root.replace('/','_')+file_.split('.')[0]
		
		with fileinput.FileInput(file, inplace=True) as f:
			for line in f:
				if ('script' in line and line.strip() in changed_scripts) and not ('<!--' in line or '-->' in line):
					print("<!--comment_for_compress"+line.replace('">','" id="its_removed">')+"comment_for_compress-->".strip(), end='')
				elif ('link' in line and line.strip() in changed_styles) and not ('<!--' in line or 'comment_for_compress-->' in line):
					print("<!--comment_for_compress"+line.replace("/>",' id="its_removed"/>')+"comment_for_compress-->".strip(), end='')
				elif '<!--style_container_for_compress-->' in line:
					print('<link rel="stylesheet" href="'+self.dir+'static/css/my_compressed_css_'+file_enswith+'.css" />')
				elif '<!--script_container_for_compress-->' in line:
					print('<script src="'+self.dir+'static/js/my_compressed_js_'+file_enswith+'.js"></script>')	
				else:
					print(line, end = '')
					
		#print('scripts:',file)
		for i in changed_scripts:
			line = i.split('src="')[1].split('"')[0].replace('{$_class_->old_variables.index_path}',dir_+'/').replace('{$_class_->old_variables.THEME}',dir_+'/admin/templates/default/')
			if '{$_class_->theme_name}' in line:
				if 'inc' in file:
					line = line.replace('{$_class_->theme_name}',file.split('/')[-3])
				else:
					line = line.replace('{$_class_->theme_name}',file.split('/')[-2])
			print(line)
			scripts.append(line)
		#print('styles:',file)
		for i in changed_styles:
			line = i.split('href="')[1].split('"')[0].replace('{$_class_->old_variables.index_path}',dir_+'/').replace('{$_class_->old_variables.THEME}',dir_+'/admin/templates/default/')
			if '{$_class_->theme_name}' in line:
				if 'inc' in file:
					line = line.replace('{$_class_->theme_name}',file.split('/')[-3])
				else:
					line = line.replace('{$_class_->theme_name}',file.split('/')[-2])
			styles.append(line)
			print(line)



		if len(styles):
			if not os.path.exists(os.path.join(dir_,'static/css/my_compressed_css_'+file_enswith+'.css')):
				open(os.path.join(dir_,'static/css/my_compressed_css_'+file_enswith+'.css'),'a')
			with open(os.path.join(dir_,'static/css/my_compressed_css_'+file_enswith+'.css'),'w') as w:
				for i in styles:
					try:
						with open(i,'r') as r:
							w.write(r.read())
						w.write('\n')
					except Exception as e:
						print(e)
			with open(os.path.join(dir_,'static/css/my_compressed_css_'+file_enswith+'.css')) as css_file:
				com = compress(css_file.read())
				with open(os.path.join(dir_,'static/css/my_compressed_css_'+file_enswith+'.css'),'w') as w:
					w.write(com)
			print('minify css: ',os.path.join(dir_,'static/css/my_compressed_css_'+file_enswith+'.css'))

		if len(scripts):
			if not os.path.exists(os.path.join(dir_,'static/js/my_compressed_js_'+file_enswith+'.js')):
				open(os.path.join(dir_,'static/js/my_compressed_js_'+file_enswith+'.js'),'a')
			with open(os.path.join(dir_,'static/js/my_compressed_js_'+file_enswith+'.js'),'w') as w:
				for i in scripts:
					try:
						with open(i,'r') as r:
							w.write(r.read())
						w.write('\n')
					except Exception as e:
						print(e)
			with open(os.path.join(dir_,'static/js/my_compressed_js_'+file_enswith+'.js')) as js_file:
				minified = jsmin(js_file.read(), quote_chars="'\"`")
				with open(os.path.join(dir_,'static/js/my_compressed_js_'+file_enswith+'.js'),'w') as w:
					w.write(minified)
			print('minify js: ',os.path.join(dir_,'static/js/my_compressed_js_'+file_enswith+'.js'))

	def restore_progress(self):
		pass


      

if __name__ == "__main__":

	try:
		import sys,os,time,multiprocessing,threading,http.client,urllib
		from bs4 import BeautifulSoup, Comment
		import fileinput
		from optparse import OptionParser
		from jsmin import jsmin
		from csscompressor import compress


		parser = OptionParser()
		parser.add_option("-c", "--command", dest="command",help="replace or restore",default="replace")

		(options, args) = parser.parse_args()
		options = vars(options)
		# options['MESSAGE'] = options['MESSAGE'].replace('-',';').replace(',',' ')


	
		

		dir_ = '/var/www/kharagauli_new'
		os.chdir(dir_)

		a = compress_files()


	except ImportError as e:
		sys.exit(e)
	except Exception as e:
		print('error was',e)





