#include <pthread.h>
#include <iostream>
#include <ctime>
#include "mns/mns_client.h"

using namespace std;
using namespace mns::sdk;

const long total_seconds = 30;
const long thread_size = 200;

QueuePtr queuePtr;

string trim(string& s)
{
    int n;
    for (n = s.size() - 1; n >= 0; n--)
    {
        if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n' && s[n] != '\r')
        {
            break;    
        }
    }
    return s.substr(0, n+1);
}

void readConfig(string& endpoint, string& accessId, string& accessKey, string& stsToken)
{
    stsToken = "";
    ifstream is_file("aliyun-mns.properties");
    std::string line;
    while( std::getline(is_file, line) )
    {
        std::istringstream is_line(line);
        std::string key;
        if( std::getline(is_line, key, '=') )
        {
            std::string value;
            if( std::getline(is_line, value) )
            {
                if (key == "mns.accountendpoint")
                {
                    endpoint = trim(value);
                }
                else if (key == "mns.accesskeyid")
                {
                    accessId = trim(value);
                }
                else if (key == "mns.accesskeysecret")
                {
                    accessKey = trim(value);
                }
                else if (key == "mns.ststoken")
                {
                    stsToken = trim(value);
                }
            }
        }
    }
}

void* func(void* args)
{
    long count = 0;
    SendMessageResponse resp;
    std::time_t start = std::time(NULL);
    while (true)
    {
        for (int i = 0; i < 50; ++i)
        {
            queuePtr->sendMessage("test", resp);
        }
        count += 50;

        std::time_t end = std::time(NULL);
        if (end - start >= total_seconds)
        {
            pthread_exit((void*)count);
            return (void*) count;
        }
    }
}

int main()
{
    string endpoint;
    string accessId;
    string accessKey;
    string stsToken;
    readConfig(endpoint, accessId, accessKey, stsToken);
    MNSClient mnsClient(endpoint, accessId, accessKey, stsToken);

    queuePtr = mnsClient.createQueue("TestCplusplusSDKQ");

    pthread_t tid[thread_size];

    for (int i = 0; i < thread_size; i++)
    {
        pthread_create(&tid[i], NULL, &func, NULL);
    }

    long totalCount = 0;
    for (int i = 0; i < thread_size; i++)
    {
        void* count = 0;
        pthread_join(tid[i], &count);
        totalCount += (long)count;
    }
    cout << totalCount << endl;
    cout << totalCount / total_seconds << endl;
    return 0;
}
