#!/usr/bin/env python
# coding=utf-8
import math
import os
from flask.ext.login import login_required
from flask import request

def pager(step, showSize, current, itemsNum):  # 分页函数
    '''
		step:
			每页显示item的个数
		showSize:
			页面显示分页导航数字的个数
		current:
			当前第几页
		itemsNum:
			items的总个数
		输出
		startPage:
			从第几页开始计数
		endPage:
			到第几页结束
		例如
		1---->5
			______________showSize=5_____________
            |		                            |
		    1        2        3        4        5
		startPage           current          endPage
    '''
    pages = math.ceil(itemsNum / step)
    pO = math.floor(showSize / 2)
    if pages < showSize:
        startPage = 1
        endPage = pages
    if pages >= showSize and current <= pO:
        startPage = 1
        endPage = showSize
    if pages >= showSize and current > pO and current + pO <= pages:
        startPage = current - pO
        endPage = showSize+startPage-1
    if pages >= showSize and current > pO and current + pO > pages:
        startPage = pages - showSize+1
        endPage = pages
    return {"startPage": startPage, "endPage": endPage}


@login_required
def config_modify():
	config_dict={}
	file = os.path.join(os.getcwd(),'flaskcms','config.py')
	try:
		with open(file,'r',encoding='utf8') as f:
			for line in f.readlines():
				a,b = line.split('=',1)
				config_dict.update({a.strip():b})
		for key in request.form.keys():
			if key in config_dict.keys():
				config_dict.update({key:request.form.get(key,"")+'\n'})
		with open(file,'w',encoding='utf8') as f:
			for key,value in config_dict.items():
				f.write(key+" = "+value)
		return '{"status":"success"}'
	except Exception as e:
		return '{"status":"error"}'