const http = require('http')
// const tgclient = require('./tgclient')
// const logger = require('./logger')
const { Client } = require('tdl')
const { TDLib } = require('tdl-tdlib-addon')
var path = require('path');

const tgclient = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), {
  apiId: 234569,
  apiHash: 'ee77bf549e61d3de158916126c8ef7dd'
})

tgclient.on('error', console.error)
tgclient.on('update', update => {
  console.log('Received update:', update)
})

async function main () {
  await tgclient.connectAndLogin()

  console.log(await tgclient.invoke({ _: 'getMe' }))

  // ...
}

main().catch(console.error)



var myNumber = 1;

const host = '192.168.130.10'
const port = 51000

function notFound(res) {
  res.statusCode = 404
  res.setHeader('Content-Type', 'text/plain')
  res.end('Not found\n')
}

const server = http.createServer((req, res) => {
	//getAuthorizationState
	myNumber = myNumber+1;
	console.log(' ')
	console.log(' ')
	console.log('---=======- [ '+myNumber+' ] ---------')
	console.log('This is the METHOD:' + req.method)
	console.log('This is the URL:' + req.url)
	console.log('This is the REQUEST Hdrs:')
	
	console.log(req.headers)
	
	switch (req.method) { 
		case 'GET': {
			switch (req.url) {
				case '/home': {
					res.statusCode = 200
					res.setHeader('Content-Type', 'text/plain')
					res.end('Home page\n')
					break
				}
				case '/about': {
					res.statusCode = 200
					res.setHeader('Content-Type', 'text/plain')
					res.end('About page\n')
					break
				}
				case '/test': {
					
					tgclient.invoke({
					  _: 'sendMessage',
					  chat_id: 124987160,
					  input_message_content: {
						_: 'inputMessageText',
						text: {
						  _: 'formattedText',
						  text: '👻 Test 123'
						}
					  }
					})
					
					res.statusCode = 200
					res.setHeader('Content-Type', 'text/plain')
					res.end('About page\n')
					break
				}
				case '/': {
					res.statusCode = 200
					res.setHeader('Content-Type', 'text/plain')
					res.end('Hello main\n')
					break
				}
				default: {
					notFound(res)
					break
				}
			}
			break
		}
		case 'POST': {
		  switch (req.url) {
			case '/api/admin': {
				res.statusCode = 200
				res.setHeader('Content-Type', 'text/plain')
				res.end('Create admin request\n')
				break
			}
			case '/api/user': {
				res.statusCode = 200
				res.setHeader('Content-Type', 'text/plain')
				res.end('Create user request\n')
				break
			}
			default: {
				notFound(res)
				break
			}
		  }

		  break
		}
		default: {
		  notFound(res)
		  break
		}
	}
})

server.listen(port, host, () => {
  console.log(`Server listens http://${host}:${port}`)
})