# -*- coding: utf-8 -*-

#	Copyright © 2014 dyknon
#
#	This file is part of Pylib-nicovideo.
#
#	Pylib-nicovideo is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

from . import err
import http.client
import re
import os
import time

def http_get_text_data(server, path):
	#httpを使ってテキストをダウンロードして返す。
	#ヘッダから文字コードを取得するのが面倒な時用
	#しかしこんなの、標準ライブラリ探したら出てきそうである。

	conn = http.client.HTTPConnection(server)
	conn.request("GET", path)
	res = conn.getresponse()
	if res.status == 200:
		contype = res.getheader("Content-Type")
		if contype:
			index = contype.find("charset=")
			if index != -1:
				charset = contype[index+len("charset="):]
				index = charset.find(";")
				if index != -1:
					charset = charset[:index]
				return res.read().decode(charset, "replace")
		return res.read().decode("utf-8", "replace")
	else:
		conn.close()
		raise err.HttpErr(res.status, res.reason)
	conn.close()

def un_javascript_escape(text):
	#javascriptの文字列中の\t, \n, \u**** などをどうにかする

	def unicode_replacer(mo):
		return chr(int(mo.group(1), 16))
	def escaped_symbol_replacer(mo):
		return mo.group(1)

	ret = text
	ret = ret.replace("\\t", "\t")
	ret = ret.replace("\\n", "\n")
	ret = re.sub(r"\\u([0-9a-fA-F]{4})", unicode_replacer, ret)
	ret = re.sub(r"\\(.)", escaped_symbol_replacer, ret)
	return ret

def xml_unref(text):
	#XML内の実体参照,文字参照の置き換え

	def unicode_replacer10(mo):
		return chr(int(mo.group(1)))
	def unicode_replacer16(mo):
		return chr(int(mo.group(1), 16))

	ret = text.replace("&amp;", "&")
	ret = ret.replace("&lt;", "<")
	ret = ret.replace("&gt;", ">")
	ret = ret.replace("&apos;", "'")
	ret = ret.replace("&quot;", "\"")
	ret = re.sub(r"&#([0-9]+);", unicode_replacer10, ret)
	ret = re.sub(r"&#x([0-9a-fA-F]+);", unicode_replacer16, ret)
	return ret

def filename_fixer(name):
	#OSに応じてファイル名に使用不能な文字を置き換え
	#大体_になる。あと、各OSの文化をあんまり知らんからテキトー
	#というか、上の3つ以外でこのツール動かす人いないだろ
	if os.name == "posix":
		return name.replace("/", "_")
	elif os.name == "nt":
		nname = name
		for c in "\\/:*?\"<>|":
			nname = nname.replace(c, "_")
		return nname
	elif os.name == "mac":
		nname = name
		#念の為:と/両方回避しておく
		for c in "/:":
			nname = nname.replace(c, "_")
		return nname
	elif os.name == "os2":
		spn = name.split(".")
		name = ".".join(spn[:len(spn)-1])
		ext = spn[len(spn)-1]
		nname = ""
		for c in name:
			for a in "!#$%&'()*+-0123456789<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`^_{}~":
				if a == c:
					nname += c
					break
			else:
				nname += "_"
		nname = nname[:8]
		for na in ["CON", "AUX", "COM1", "COM2", "COM3", "COM4",
				   "LPT1", "LPT2", "LPT3", "PRN", "NUL"]:
			if nname == na:
				nname += "_"
				break
		nex = ""
		for c in ext:
			for a in "!#$%&'()*+-0123456789<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`^_{}~":
				if a == c:
					nex += c
					break
			else:
				nex += "_"
		nname += "." + nex[:3]
		return nname
	elif os.name == "riscos":
		nname = name
		#よくわかんないけどこんな感じ?
		nname = nname.replace(".", "/")
		nname = nname.replace("$", "_")
		return nname
	else:
		#ISOで使用可能な名前のみ付ける
		#POSIXの時と同じ処理でも良かったかもなぁ
		spn = name.split(".")
		name = ".".join(spn[:len(spn)-1])
		ext = spn[len(spn)-1]
		nname = ""
		for c in name:
			for a in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_":
				if a == c:
					nname += c
					break
			else:
				nname += "_"
		nname = "{:_<8}".format(nname[:8])
		nex = ""
		for c in ext:
			for a in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_":
				if a == c:
					nex += c
					break
			else:
				nex += "_"
		nex = "{:_<8}".format(nex[:8])
		nname += "." + nex
		return nname

def parse_time(text):
	#Pythonのライブラリがタイムゾーンに:が含まれるとエラーを吐くので
	#ちょっと細工します。
	if text.count(":") == 3:
		ttl = text.split(":")
		tt = ":".join(ttl[:3]) + ttl[3]
	else:
		tt = text
	return time.strptime(tt, "%Y-%m-%dT%H:%M:%S%z")
