from http.server import BaseHTTPRequestHandler, HTTPServer
from xml.etree import ElementTree as ET
import json
import random
import smtplib
import os
from email.mime.text import MIMEText

HOST_NAME = 'localhost'
PORT_NUMBER = 8000
# Глобальный объект сервера
server = None
class MyHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == 'http://localhost:8000/send_code':
            self.handle_send_code()
        elif self.path == 'http://localhost:8000/register':
            self.handle_registration()
        else:
            self.send_error(404, 'Not Found')

    def handle_send_code(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        data = json.loads(body)
        email = data['email']

        # Проверка на Gmail
        if not email.endswith('@gmail.com'):
            self.send_response(400)
            self.send_header('Content-type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.end_headers()
            self.wfile.write(bytes('Пожалуйста, введите адрес электронной почты Gmail.', 'utf-8'))
            return

        code = str(random.randint(100000, 999999))

        try:
            msg = MIMEText(f'Ваш код подтверждения: {code}')
            msg['Subject'] = 'Код подтверждения'
            msg['From'] = 'damirka20051904@gmail.com'  # Замените на ваш адрес
            msg['To'] = email

            with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
                server.login('damirka20051904@gmail.com', 'DaMiR_2005')  # Замените на ваш логин и пароль
                server.sendmail('damirka20051904@gmail.com', email, msg.as_string())

            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.end_headers()
            self.wfile.write(bytes('Код успешно отправлен', 'utf-8'))
        except Exception as e:
            self.send_response(500)
            self.send_header('Content-type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.end_headers()
            self.wfile.write(bytes(f'Ошибка отправки кода: {e}', 'utf-8'))

    def handle_registration(self):
        # Получаем XML-данные из запроса
        content_length = int(self.headers['Content-Length'])
        xml_data = self.rfile.read(content_length).decode('utf-8')

        # Парсим XML-данные
        root = ET.fromstring(xml_data)

        # Извлекаем информацию из XML
        name = root.find('name').text
        phone = root.find('phone').text
        email = root.find('email').text
        code = root.find('code').text
        password = root.find('password').text

        # Сохраняем данные в файл users.xml
        with open('registrations.xml', 'a', encoding='utf-8') as f:
            f.write(f"""
                <user>
                    <name>{name}</name>
                    <phone>{phone}</phone>
                    <email>{email}</email>
                    <code>{code}</code>
                    <password>{password}</password>
                </user>
            """)

        # Отправляем ответ на AJAX-запрос
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
        self.wfile.write(bytes('Данные успешно записаны', 'utf-8'))

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == 'документы/Устав.docx':
            self.handle_file_download('Устав.docx')
        else:
            self.send_error(404, 'Not Found')

    def handle_file_download(self, filename):
        try:
            with open(filename, 'rb') as f:
                self.send_response(200)
                self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
                self.end_headers()
                self.wfile.write(f.read())
        except FileNotFoundError:
            self.send_error(404, 'File not found')

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == 'документы/Инструкция выгрузка подписи.docx':
            self.handle_file_download('Инструкция выгрузка подписи.docx')
        else:
            self.send_error(404, 'Not Found')

    def handle_file_download(self, filename):
        try:
            with open(filename, 'rb') as f:
                self.send_response(200)
                self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
                self.end_headers()
                self.wfile.write(f.read())
        except FileNotFoundError:
            self.send_error(404, 'File not found')

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == 'документы/РП_Данные_ГИС_ЖКХ_2_1_v1.docx':
            self.handle_file_download('РП_Данные_ГИС_ЖКХ_2_1_v1.docx')
        else:
            self.send_error(404, 'Not Found')

    def handle_file_download(self, filename):
        try:
            with open(filename, 'rb') as f:
                self.send_response(200)
                self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
                self.end_headers()
                self.wfile.write(f.read())
        except FileNotFoundError:
            self.send_error(404, 'File not found')

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == 'документы/РП_Оперативные_оповещения_2_1_v1.docx':
            self.handle_file_download('РП_Оперативные_оповещения_2_1_v1.docx')
        else:
            self.send_error(404, 'Not Found')

    def handle_file_download(self, filename):
        try:
            with open(filename, 'rb') as f:
                self.send_response(200)
                self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
                self.end_headers()
                self.wfile.write(f.read())
        except FileNotFoundError:
            self.send_error(404, 'File not found')

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == 'документы/регион_РП_Сообщения_жителей_2_1_v1.docx':
            self.handle_file_download('регион_РП_Сообщения_жителей_2_1_v1.docx')
        else:
            self.send_error(404, 'Not Found')

    def handle_file_download(self, filename):
        try:
            with open(filename, 'rb') as f:
                self.send_response(200)
                self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
                self.end_headers()
                self.wfile.write(f.read())
        except FileNotFoundError:
            self.send_error(404, 'File not found')

if __name__ == '__main__':
    # Создание глобального объекта сервера
    server = HTTPServer((HOST_NAME, PORT_NUMBER), MyHandler)
    print(f'Сервер запущен на http://{HOST_NAME}:{PORT_NUMBER}')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
        print('Сервер остановлен')